package com.transaction.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.transaction.common.base.User;
import org.apache.commons.collections4.map.HashedMap;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class JwtTokenUtil {


    //公钥
    public  static String SIMULATE_SECRET = "transaction-simulate";

    //公钥
    public  static String MANAGE_SECRET = "transaction-manage";

    // 有效时长毫秒数
    private static final long EXPIRE_TIME = 30 * 60 * 1000;


    /**
     * 生成token
     * @return
     */
    public static String creatToken(User user,String secret){
        //签发时间
        Date date = new Date();

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        //登录名
        String accountName = user.getAccountName();
        //用户Id
        String userCode = user.getUserCode();

        //生成token
        String token = JWT.create()
                .withHeader(map)
                .withClaim("userCode",userCode)
                .withClaim("accountName",accountName)
                .withIssuedAt(date)
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    public static Map<String, Claim> verifyToken(String token,String secret){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT jwt = null;
        try{
            jwt = jwtVerifier.verify(token);
        }catch (Exception e ){
            e.printStackTrace();
            return null;
        }

        return jwt.getClaims();
    }
}